//
//  DLBaseTextView.m
//  Base
//
//  Created by 高安宏 on 2017/4/5.
//  Copyright © 2017年 dgg. All rights reserved.
//

#import "DLBaseTextView.h"
#import <Masonry/Masonry.h>
#import "UIView+Extension.h"
#import <objc/runtime.h>

#define PlaceholderBaseX 5.0f
#define PlaceholderBaseY 8.0f
#define UsedNumberHeight 20.0f
#define DefaultTextNumber 200
#define DefaultText @""
#define TextFont self.font.pointSize

@interface DLBaseTextView ()

//占位imageView
@property (nonatomic, strong)UIImageView *placeholderImageView_dgg;
//占位符Label
@property (nonatomic, strong)UILabel *placeholderLabel_dgg;
//实际文本
@property (nonatomic, copy)NSString *actualText_dgg;
//字数限制背景
@property (nonatomic, strong)UIView *numberBackView;
//已输入字数Label
@property (nonatomic, strong)UILabel *usedNumber_dgg;

@end

//IB_DESIGNABLE
@implementation DLBaseTextView

@synthesize textNumber_dgg = _textNumber_dgg;

#pragma mark - init -

- (void)layoutSubviews {
    [super layoutSubviews];
    if (!self.isShowtextNumber_dgg) {
        [self.superview addSubview:self.numberBackView];
        [self.numberBackView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.mas_leading);
            make.top.equalTo(self.mas_bottom).offset(-UsedNumberHeight);
            make.width.equalTo(self.mas_width);
            make.height.mas_offset(UsedNumberHeight);
        }];
        [self.numberBackView addSubview:self.usedNumber_dgg];
        [self.usedNumber_dgg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 5));
        }];
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer {
    self = [super initWithFrame:frame textContainer:textContainer];
    if (self) {
        [self setUI];
    }
    return self;
}

-(void)setUI{
    
    self.textAlignment = NSTextAlignmentLeft;
    self.contentInset = UIEdgeInsetsMake(self.contentInset.top, self.contentInset.left, UsedNumberHeight, self.contentInset.right);
    self.actualText_dgg = DefaultText;
    self.delegate = self;
    if (!self.font) {
        self.font = [UIFont systemFontOfSize:14];
    }
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
    _numberBackView.backgroundColor = backgroundColor;
}

- (void)setHidden:(BOOL)hidden
{
    [super setHidden:hidden];
    self.numberBackView.hidden = hidden;
}

-(void)setIsShowtextNumber_dgg:(BOOL)isShowtextNumber_dgg
{
    _isShowtextNumber_dgg = isShowtextNumber_dgg;
    if (isShowtextNumber_dgg) {
        self.contentInset = UIEdgeInsetsZero;
        [self.numberBackView removeFromSuperview];
    }
}

- (void)removeFromSuperview
{
    [super removeFromSuperview];
    [self.numberBackView removeFromSuperview];
}

#pragma mark - getterAndSetter -

- (UIView *)numberBackView
{
    if (!_numberBackView) {
        _numberBackView = [UIView new];
        _numberBackView.backgroundColor = self.backgroundColor;
    }
    return _numberBackView;
}

- (UILabel *)usedNumber_dgg
{
    if (!_usedNumber_dgg) {
        _usedNumber_dgg = [UILabel new];
        _usedNumber_dgg.font = [UIFont systemFontOfSize:12];
        _usedNumber_dgg.textColor = PlaceholderColor;
        _usedNumber_dgg.text = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.actualText_dgg.length,(unsigned long)self.textNumber_dgg];
        _usedNumber_dgg.textAlignment = NSTextAlignmentRight;
    }
    return _usedNumber_dgg;
}

- (UILabel *)placeholderLabel_dgg
{
    if (!_placeholderLabel_dgg) {
        float height = [self.placeholder_dgg getHeightWithFontSize:TextFont width:self.width];
        _placeholderLabel_dgg = [[UILabel alloc] initWithFrame:CGRectMake(PlaceholderBaseX, PlaceholderBaseY, self.width-2*PlaceholderBaseX, height)];
        _placeholderLabel_dgg.font = self.font;
        _placeholderLabel_dgg.numberOfLines = 0;
        _placeholderLabel_dgg.text = self.placeholder_dgg;
        _placeholderLabel_dgg.textColor = PlaceholderColor;
        _placeholderLabel_dgg.hidden = YES;
        [self addSubview:_placeholderLabel_dgg];
        
        [_placeholderLabel_dgg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.placeholderImageView_dgg.mas_trailing).mas_offset(self.placeholderImage_dgg?2:0);
            make.top.equalTo(self.mas_top).mas_offset(PlaceholderBaseY);
            make.width.equalTo(self).mas_offset(-PlaceholderBaseX*2);
        }];
    }
    return _placeholderLabel_dgg;
}

- (UIImageView *)placeholderImageView_dgg {
    if (!_placeholderImageView_dgg) {
        _placeholderImageView_dgg = [[UIImageView alloc] initWithFrame:CGRectMake(PlaceholderBaseX, PlaceholderBaseY+2, TextFont, TextFont)];
        _placeholderImageView_dgg.hidden = YES;
        [self addSubview:_placeholderImageView_dgg];
        
        [_placeholderImageView_dgg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.mas_leading).mas_offset(PlaceholderBaseX);
            make.top.equalTo(self.mas_top).mas_offset(PlaceholderBaseY+2);
            make.width.and.height.mas_equalTo(self.placeholderImage_dgg?TextFont:0);
        }];
    }
    return _placeholderImageView_dgg;
}

- (NSString *)placeholder_dgg {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setPlaceholder_dgg:(NSString *)placeholder_dgg {
    objc_setAssociatedObject(self, @selector(placeholder_dgg), placeholder_dgg, OBJC_ASSOCIATION_COPY_NONATOMIC);
    if (![NSString isEmpty:placeholder_dgg]) {
        self.placeholderLabel_dgg.text = self.placeholder_dgg;
    } else {
        self.placeholderLabel_dgg.text = nil;
    }
    
    
    self.placeholderLabel_dgg.hidden = self.text.length >0;
}

- (UIImage *)placeholderImage_dgg {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setPlaceholderImage_dgg:(UIImage *)placeholderImage_dgg {
    objc_setAssociatedObject(self, @selector(placeholderImage_dgg), placeholderImage_dgg, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (placeholderImage_dgg) {
        self.placeholderImageView_dgg.image = self.placeholderImage_dgg;
        [_placeholderImageView_dgg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.and.height.mas_equalTo(TextFont);
        }];
        [_placeholderLabel_dgg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(_placeholderImageView_dgg.mas_trailing).mas_offset(2);
            make.top.equalTo(self.mas_top).mas_offset(PlaceholderBaseY);
            make.width.equalTo(self).mas_offset(-PlaceholderBaseX*2);
        }];
    } else {
        self.placeholderImageView_dgg.image = nil;
        [_placeholderImageView_dgg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.and.height.mas_equalTo(0);
        }];
        
        [_placeholderLabel_dgg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(_placeholderImageView_dgg.mas_trailing).mas_offset(0);
            make.top.equalTo(self.mas_top).mas_offset(PlaceholderBaseY);
            make.width.equalTo(self).mas_offset(-PlaceholderBaseX*2);
        }];
    }
    
    self.placeholderImageView_dgg.hidden = self.text.length > 0;
}

- (NSUInteger)textNumber_dgg {
    NSNumber *number = objc_getAssociatedObject(self, _cmd);
    if (!number || number <= 0) {
        objc_setAssociatedObject(self, _cmd, @(DefaultTextNumber), OBJC_ASSOCIATION_RETAIN);
        number = objc_getAssociatedObject(self, _cmd);
    }
    return [number unsignedIntegerValue];
}

- (void)setTextNumber_dgg:(NSUInteger)textNumber_dgg {
    if (textNumber_dgg <= 0) {
        textNumber_dgg = 200;
    }
    objc_setAssociatedObject(self, @selector(textNumber_dgg), @(textNumber_dgg), OBJC_ASSOCIATION_RETAIN);
    _usedNumber_dgg.text = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.actualText_dgg.length,(unsigned long)textNumber_dgg];
    if (self.text.length > textNumber_dgg) {
        self.text = [self.actualText_dgg substringToIndex:textNumber_dgg];
    }
}

#pragma mark - UITextViewDelegate -
- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > self.textNumber_dgg) { //字数限制
        textView.text =  [textView.text substringToIndex:self.textNumber_dgg];
        [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 1)];
    }
    
    if ([NSString isEmpty:textView.text.trimString]) {
        self.actualText_dgg  = DefaultText;
    }else if ([[[textView textInputMode]primaryLanguage] isEqualToString:@"emoji"] || [self isContainsTwoEmoji:textView.text]) { //限制输入表情
        if (!self.isEmoji) {
            textView.text = self.actualText_dgg;
        }
    }else {
        self.actualText_dgg = textView.text;
    }
    
    if (self.textHadChange) {
        self.textHadChange(self.actualText_dgg);
    }
    
    _usedNumber_dgg.text = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.actualText_dgg.length,(unsigned long)self.textNumber_dgg];
    
    if (textView.text.length > 0) { //占位符显示隐藏
        self.placeholderLabel_dgg.hidden = YES;
        self.placeholderImageView_dgg.hidden = YES;
    } else {
        self.placeholderLabel_dgg.hidden = NO;
        self.placeholderImageView_dgg.hidden = NO;
    }
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    self.actualText_dgg = text;
    if (![NSString isEmpty:text]) {
        self.placeholderLabel_dgg.hidden = YES;
        self.placeholderImageView_dgg.hidden = YES;
    }else
    {
        self.placeholderLabel_dgg.hidden = NO;
        self.placeholderImageView_dgg.hidden = NO;
    }
    self.usedNumber_dgg.text = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.text.length,(unsigned long)self.textNumber_dgg];
}

#pragma mark -
//限制输入表情
- (BOOL)isContainsTwoEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }else if (hs == 0x200d){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}



/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
